<?php

namespace Home\Controller;

use Think\Controller;

use Common\Ext\Ethereum_Transaction;

class FinanceController extends HomeController
{

    public function myzr($userid,$coin,$token)
    //public function myzr($userid,$token,$coin)
    {
//        if (!userid()) {
//            $this->ajaxError('请先登陆');
//        }

        $this->checkLog($userid,$token);

        $user = D('User')->where('id = ' . $userid)->find();

//        if (!$user['truename']) {
//            $this->ajaxError('请先完成实名认证');
//        }
//
//        if (!$user['paypassword']) {
//            $this->ajaxError('请先设置交易密码');
//        }

        if (C('coin')[$coin]) {
            $coin = trim($coin);
        } else {
            $coin = C('xnb_mr');
        }

        if (C('coin')[$coin]) {
            $coin = trim($coin);
        } else {
            $coin = C('xnb_mr');
        }

        $Coin = C('Coin');
        foreach ($Coin as $k => $v) {
            $coin_list[$v['name']] = $v;
        }
        unset($coin_list['cny']);
        $user_coin = M('UserCoin')->where(array(
            'userid' => $userid
        ))->find();
//        $user_coin = M('UserCoin')->where(array(
//            'userid' => 1
//        ))->find();

        $Coin = M('Coin')->where(array(
            'name' => $coin
        ))->find();

        if (!$Coin['zr_jz']) {
            $qianbao = '当前币种禁止转入';
        } else {
            //$qbdz = $coin . 'b';
            $qbdz = 'btcb';
            if (!$user_coin[$qbdz]) {
                if ($Coin['type'] == 'qbb') {
                    $dj_username = $Coin['dj_yh'];
                    $dj_password = $Coin['dj_mm'];
                    $dj_address = $Coin['dj_zj'];
                    $dj_port = $Coin['dj_dk'];

                    $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1);
                    $json = $CoinClient->getinfo();

                    if ($CoinClient) {
                        if (!isset($json['version']) || !$json['version']) {
                            $this->ajaxError('钱包链接失败');
                        }

                        //TODO 测试参数替换
                        $qianbao_addr = $CoinClient->getaddressesbyaccount($user['username']);

                        if (!is_array($qianbao_addr)) {
                            $qianbao_ad = $CoinClient->getnewaddress($user['username']);

                            if (!$qianbao_ad) {
                                $this->ajaxError('生成钱包地址出错');
                            } else {
                                $qianbao = $qianbao_ad;
                            }
                        } else {
                            $qianbao = $qianbao_addr[0];
                        }
                    }else{
                        $where['userid'] = $userid;
                        $where['coinname'] = $coin;
                        $Moble = M('Myzr');
                        $list = $Moble->where($where)
                            ->order('id desc')
                            ->select();
                        $data = array(
                            'btc' => $user_coin['btc'],
                            'btcd' => $user_coin['btcd'],
                            'btctotal' => $user_coin['btc'] + $user_coin['btcd'],
                            //'qiaobao' => $qianbao,
                            'tradelog' => $list
                        );

                        $this->ajaxReturn($data,'JSON');
                    }

                }

//                if ($Coin['type'] == 'eth') {
//                    $dj_address = $Coin['dj_zj'];
//                    $dj_port = $Coin['dj_dk'];
//                    $eth = new \Common\Ext\Ethereum($dj_address, $dj_port);
//                    if (!$eth->eth_protocolVersion()) {
//                        $this->ajaxError('钱包链接失败');
//                    } else {
//                        $pass = createRandomStr(16);
//                        $qianbao = $eth->personal_newAccount($pass);
//                        $rs = M('UserCoin')->where(array(
//                            'userid' => $userid
//                        ))->save(array(
//                            $coin . 's' => $pass
//                        ));
//                    }
//                }

                if (!$qianbao) {
                    $this->ajaxError('生成钱包地址出错');
                }

                $rs = M('UserCoin')->where(array(
                    'userid' => $userid
                ))->save(array(
                    'btcb' => $qianbao
                    //$coin.'b' => $qianbao
                ));

                if (!$rs) {
                    $this->ajaxError('生成钱包地址出错');
                }
            } else {

                //TODO 测试参数替换
                //$qianbao = $user_coin[$coin . 'b'];
                $qianbao = $user_coin['btcb'];
            }
        }
        $where['userid'] = $userid;
        $where['coinname'] = $coin;
        $Moble = M('Myzr');
//        $count = $Moble->where($where)->count();
//        $Page = new \Think\Page($count, 10);
//        $show = $Page->show();
        $list = $Moble->where($where)
            ->order('id desc')
            ->select();

       // echo $qianbao;
        $data = array(
            'btc' => $user_coin['btc'],
            'btcd' => $user_coin['btcd'],
            'btctotal' => $user_coin['btc'] + $user_coin['btcd'],
            'qiaobao' => $qianbao,
            'tradelog' => $list
        );

        $this->ajaxReturn($data,'JSON');
//        $this->assign('coin_list', $coin_list);
//        $this->assign('xnb', $coin);
//        $this->assign('user_coin', $user_coin);
//        $this->assign('zr_jz', $Coin['zr_jz']);
//        $this->assign('user', $user);
//        $this->assign('list', $list);
//        $this->assign('page', $show);
//        $this->assign('qianbao', $qianbao);
    }


    public function upmyzc($coin, $num, $addr, $paypassword, $userid, $token)
//    public function upmyzc($coin = 'bacc', $num = 0.3 , $paypassword , $addr = 'CbDNoBiLN44T1Zi6EeG8yCoZPqsT49Ex9y' , $userid = 32 , $remark)
    {
        $this->checkLog($userid,$token);

        $num = abs($num);

        if (!check($num, 'currency')) {
            $this->ajaxError('数量格式错误');
        }

        if (!check($addr, 'dw')) {
            $this->ajaxError('钱包地址格式错误!');
        }

        if (!check($paypassword, 'password')) {
            $this->ajaxError('交易密码格式错误');
        }

        if (!check($coin, 'n')) {
            $this->ajaxError('币种格式错误');
        }

        if (!C('coin')[$coin]) {
            $this->ajaxError('当前币种错误');
        }

        $Coin = M('Coin')->where(array(
            'name' => $coin
        ))->find();

        if (!$Coin) {
            $this->ajaxError('当前币种错误');
        }
        $myzc_min = ($Coin['zc_min'] ? abs($Coin['zc_min']) : 0.0001);
        $myzc_max = ($Coin['zc_max'] ? abs($Coin['zc_max']) : 10000000);

        if ($num < $myzc_min) {
            $this->ajaxError('转出数量超过系统最小限制{$num}!', array('num' => number_format($myzc_min)));
        }

        if ($myzc_max < $num) {
            $this->ajaxError('转出数量超过系统最大限制{$num}!', array('num' => number_format($myzc_max)));
        }

        $user = M('User')->where(array(
            'id' => $userid
        ))->find();

//        if (md5($paypassword) != $user['paypassword']) {
//            $this->ajaxError('交易密码错误');
//        }

        $user_coin = M('UserCoin')->where(array(
            'userid' => $userid
        ))->find();

        if ($user_coin[$coin] < $num) {
            $this->ajaxError('{$coin}可用余额不足', array('coin' => $coin));
        }

        $qbdz = $coin . 'b';
        $fee_user = M('UserCoin')->where(array(
            $qbdz => $Coin['zc_user']
        ))->find();

//        if ($fee_user) {
//            $fee = round((($num - $Coin['zc_fee_two']) / 100) * $Coin['zc_fee'] + $Coin['zc_fee_two'], 8);
//            $mum = round($num - $fee, 8);
//
//            if ($mum < 0) {
//                $this->ajaxError('转出手续费错误');
//            }
//
//            if ($fee < 0) {
//                $this->ajaxError('转出手续费设置错误');
//            }
//        } else {
//            $fee = 0;
//            $mum = $num;
//        }
        $fee = 0;
        $mum = $num;
        if ($Coin['type'] == 'qbb' || $Coin['type'] == 'eth') {
            $mo = M();
            if ($mo->table('trade_user_coin')
                ->where(array(
                    $qbdz => $addr
                ))
                ->find()
            ) {
                $peer = M('UserCoin')->where(array(
                    $qbdz => $addr
                ))->find();

                if (!$peer) {
                    $this->ajaxError('转出地址不存在');
                }

                $mo = M();
                $mo->execute('set autocommit=0');
                $mo->execute('lock tables  trade_user_coin write  , trade_myzc write  , trade_myzr write');
                $rs = array();
                $rs[] = $mo->table('trade_user_coin')
                    ->where(array(
                        'userid' => $userid
                    ))
                    ->setDec($coin, $num);
                $rs[] = $mo->table('trade_user_coin')
                    ->where(array(
                        'userid' => $peer['userid']
                    ))
                    ->setInc($coin, $mum);
//                if ($fee && $Coin['zc_user']) {
//                    if ($mo->table('trade_user_coin')
//                        ->where(array(
//                            $qbdz => $Coin['zc_user']
//                        ))
//                        ->find()
//                    ) {
//                        $rs[] = $mo->table('trade_user_coin')
//                            ->where(array(
//                                $qbdz => $Coin['zc_user']
//                            ))
//                            ->setInc($coin, $fee);
//                    } else {
//                        $rs[] = $mo->table('trade_user_coin')->add(array(
//                            $qbdz => $Coin['zc_user'],
//                            $coin => $fee
//                        ));
//                    }
//                }
                $rs[] = $mo->table('trade_user_coin')->add(array(
                    $qbdz => $Coin['zc_user'],
                    $coin => $fee
                ));
                $rs[] = $mo->table('trade_myzc')->add(array(
                    'userid' => $userid,
                    'username' => $addr,
                    'coinname' => $coin,
                    'txid' => md5($addr . $user_coin[$coin . 'b'] . time()),
                    'num' => $num,
                    'fee' => $fee,
                    'mum' => $mum,
                    'addtime' => time(),
                    'endtime' => time(),
                    'status' => 1
                ));
                $rs[] = $mo->table('trade_myzr')->add(array(
                    'userid' => $peer['userid'],
                    'username' => $user_coin[$coin . 'b'],
                    'coinname' => $coin,
                    'txid' => md5($user_coin[$coin . 'b'] . $addr . time()),
                    'num' => $num,
                    'fee' => $fee,
                    'mum' => $mum,
                    'addtime' => time(),
                    'endtime' => time(),
                    'status' => 1
                ));

//                if ($fee_user) {
//                    $rs[] = $mo->table('hketrade_myzc_fee')->add(array(
//                        'userid' => $fee_user['userid'],
//                        'username' => $Coin['zc_user'],
//                        'coinname' => $coin,
//                        'txid' => md5($user_coin[$coin . 'b'] . $Coin['zc_user'] . time()),
//                        'num' => $num,
//                        'fee' => $fee,
//                        'type' => 1,
//                        'mum' => $mum,
//                        'addtime' => time(),
//                        'status' => 1
//                    ));
//                }
                if (check_arr($rs)) {
                    $mo->execute('commit');
                    $mo->execute('unlock tables');
                    $this->ajaxSuccess('转账成功');
                } else {
                    $mo->execute('rollback');
                    $mo->execute('unlock tables');
                    debug(implode('|', $rs), '失败');
                    $this->ajaxError('操作失败');
                }
            } else {
                $dj_username = $Coin['dj_yh'];
                $dj_password = $Coin['dj_mm'];
                $dj_address = $Coin['dj_zj'];
                $dj_port = $Coin['dj_dk'];

                if ($Coin['type'] == 'eth') {
                    $eth = new \Common\Ext\Ethereum($dj_address, $dj_port);
                    if (!$eth->eth_protocolVersion()) {
                        $this->ajaxError('钱包链接失败');
                    }
                } else {
                    $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1);
                    $json = $CoinClient->getinfo();
                    if (!isset($json['version']) || !$json['version']) {
                        $this->ajaxError('钱包链接失败');
                    }

                    $valid_res = $CoinClient->validateaddress($addr);

                    if (!$valid_res['isvalid']) {
                        $this->ajaxError($addr . '不是一个有效的钱包地址');
                    }
                }

                $auto_status = ($Coin['zc_zd'] && ($num < $Coin['zc_zd']) ? 1 : 0);

                if ($json['balance'] < $num) {
                    $this->ajaxError('钱包余额不足');
                }

                $mo = M();
                $mo->execute('set autocommit=0');
                $mo->execute('lock tables  trade_user_coin write  , trade_myzc write ,trade_myzr write ');
                $rs = array();
                $rs[] = $r = $mo->table('trade_user_coin')
                    ->where(array(
                        'userid' => $userid
                    ))
                    ->setDec($coin, $num);
                debug(array(
                    'res' => $r,
                    'lastsql' => $mo->table('trade_user_coin')->getLastSql()
                ), '更新用户人民币');
                $rs[] = $aid = $mo->table('trade_myzc')->add(array(
                    'userid' => $userid,
                    'username' => $addr,
                    'coinname' => $coin,
                    'num' => $num,
                    'fee' => $fee,
                    'mum' => $mum,
                    'addtime' => time(),
                    'status' => $auto_status
                ));
                $id = $rs[0];
//                if ($fee && $auto_status && $Coin['zc_user']) {
//                    $rs[] = $mo->table('trade_myzc_fee')->add(array(
//                        'userid' => $fee_user['userid'],
//                        'username' => $Coin['zc_user'],
//                        'coinname' => $coin,
//                        'num' => $num,
//                        'fee' => $fee,
//                        'mum' => $mum,
//                        'type' => 2,
//                        'addtime' => time(),
//                        'status' => 1
//                    ));
//
//                    if ($mo->table('trade_user_coin')
//                        ->where(array(
//                            $qbdz => $Coin['zc_user']
//                        ))
//                        ->find()
//                    ) {
//                        $rs[] = $r = $mo->table('trade_user_coin')
//                            ->where(array(
//                                $qbdz => $Coin['zc_user']
//                            ))
//                            ->setInc($coin, $fee);
//                        debug(array(
//                            'res' => $r,
//                            'lastsql' => $mo->table('trade_user_coin')->getLastSql()
//                        ), '新增费用');
//                    } else {
//                        $rs[] = $r = $mo->table('trade_user_coin')->add(array(
//                            $qbdz => $Coin['zc_user'],
//                            $coin => $fee
//                        ));
//                    }
//                }

                debug(array(
                    'res' => $r,
                    'lastsql' => $mo->table('trade_myzc')->getLastSql()
                ), '转出记录');

                if (check_arr($rs)) {
                    if ($auto_status) {
                        switch ($Coin['type']) {
//                            case 'eth':
//                                $transaction = new \Common\Ext\Ethereum_Transaction($Coin['dj_mian_address'], $addr, $eth->encode_dec($eth->to_real_value((double)$mum)));
//                                $sendrs = $eth->eth_sendTransaction($Coin['dj_mian_address'], $Coin['dj_mian_address_password'], $transaction);
//                                if ($sendrs) {
//                                    $flag = 1;
//                                    // 记录txid
//                                    $rs[] = $mo->table('hketrade_myzc')
//                                        ->where(array(
//                                            'id' => trim($id)
//                                        ))
//                                        ->save(array(
//                                            'txid' => $sendrs
//                                        ));
//                                } else {
//                                    $flag = 0;
//                                }
//                                break;
                            case 'qbb':
                                $sendrs = $CoinClient->sendtoaddress($addr, floatval($mum));
                                if ($sendrs) {
                                    $flag = 1;
                                    $arr = json_decode($sendrs, true);

                                    if (isset($arr['status']) && ($arr['status'] == 0)) {
                                        $flag = 0;
                                    }
                                    if (isset($arr['result']) && $arr['result'] != NULL) {
                                        $flag = 1;
                                        // 记录txid
                                        $rs[] = $mo->table('trade_myzc')
                                            ->where(array(
                                                'id' => trim($id)
                                            ))
                                            ->save(array(
                                                'txid' => $arr['result']
                                            ));
                                    }
                                } else {
                                    $flag = 0;
                                }
                                break;
                        }
                    }
                    if ($auto_status) {
                        $mo->execute('commit');
                        $mo->execute('unlock tables');
                        if ($flag) {
                            $this->ajaxErrot('钱包服务器转出币失败 请手动转出');
                        } else {
                            $this->ajaxSuccess('转出成功');
                        }
                    } else {
                        $mo->execute('commit');
                        $mo->execute('unlock tables');
                        $this->ajaxSuccess('转出申请成功 请等待审核');
                    }
                } else {
                    $mo->execute('rollback');
                    $mo->execute('unlock tables');
                    $this->ajaxError('转出失败');
                }
            }
        }
    }
}